using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Win32;
using Microsoft.MediaCenter.Hosting;
using Microsoft.MediaCenter.UI;
using UTorrentLib;
using Argotic.Syndication;

namespace MCEMediaManager
{
    public class Torrents : IDisposable
    {
        private Choice _DownloadingTorrents;
        private Choice _AllTorrents;
        private Choice _SeedingTorrents;
        private string _description;
        private TorrentListPage _TorrentListPageInstance;
        private TorrentSearchPage _TorrentSearchPageInstance;
        private TorrentSession _CurrentTorrentSession;
        public RegistryKey RootRegKey
        {
            get
            {
                RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\MCE Media Manager");
                if (key == null)
                    key = Registry.LocalMachine.CreateSubKey("SOFTWARE\\MCE Media Manager");
                return key;
            }
        }
        public string uTorrentServer
        {
            get
            {
                string value = (string)RootRegKey.GetValue("uTorrentServer", "servername");
                return value;
            }
        }
        public string uTorrentUsername
        {
            get
            {
                string value = (string)RootRegKey.GetValue("uTorrentUsername", "username");
               return value;
            }
        }
        public string uTorrentPassword
        {
            get
            {
                string value = (string)RootRegKey.GetValue("uTorrentPassword", "password");
                return value;
            }
        }
        public int uTorrentPort
        {
            get
            {
                int value = Convert.ToInt32(RootRegKey.GetValue("uTorrentPort", 1234));
                return value;
            }
        }
        public string Description
        {
            get { return this._description; }
            set { this._description = value; }
        }
        public TorrentSession CurrentTorrentSession
        {
            get
            {
                if (_CurrentTorrentSession == null)
                {
                    try
                    {
                        _CurrentTorrentSession = new TorrentSession(uTorrentServer, uTorrentUsername, uTorrentPassword, uTorrentPort);
                        _CurrentTorrentSession.Initialize();
                    }
                    catch
                    {
                        _CurrentTorrentSession = null;
                        Application.Current.MessageBox("Could not connect to uTorrent : " + uTorrentServer + " : " + uTorrentPort, "uTorrent Not Found", 5, false);
                    }
                }
                return _CurrentTorrentSession;
            }
        }

        public Choice SeedingTorrents
        {
            get 
            {
                if (_SeedingTorrents == null)
                    _SeedingTorrents = new Choice();
                return this._SeedingTorrents; 
            }
            set { 
                this._SeedingTorrents = value; 
            }
        }
        public Choice DownloadingTorrents
        {
            get
            {
                if (_DownloadingTorrents == null)
                    _DownloadingTorrents = new Choice();
                return _DownloadingTorrents;
            }
            set
            {
                _DownloadingTorrents = value;
            }
        }
        public Choice AllTorrents
        {
            get
            {
                if (_AllTorrents == null)
                    _AllTorrents = new Choice();
                return _AllTorrents;
            }
            set
            {
                _AllTorrents = value;
            }
        }

        public Torrents()
        {
            UpdateLists();
        }

        public void UpdateLists()
        {
            ArrayListDataSet tempDownLoading = new ArrayListDataSet();
            ArrayListDataSet tempSeeding = new ArrayListDataSet();
            ArrayListDataSet tempAll = new ArrayListDataSet();
            if (CurrentTorrentSession != null)
            {

                CurrentTorrentSession.UpdateLists();
                AddItemsToList(CurrentTorrentSession.TorrentsDownloading, ref tempDownLoading);
                AddItemsToList(CurrentTorrentSession.TorrentsAll, ref tempAll);
                AddItemsToList(CurrentTorrentSession.TorrentsSeeding, ref tempSeeding);
            }
            if (tempDownLoading.Count != 0)
                DownloadingTorrents.Options = tempDownLoading;
            else
                DownloadingTorrents = new Choice();
            if (tempAll.Count != 0)
                AllTorrents.Options = tempAll;
            else
                AllTorrents = new Choice();
            if (tempSeeding.Count != 0)
                SeedingTorrents.Options = tempSeeding;
            else
                SeedingTorrents = new Choice();
        }

        public void Dispose()
        {
            if (_DownloadingTorrents != null)
            {
                _CurrentTorrentSession = null;
                _DownloadingTorrents = null;
                _SeedingTorrents = null;
                _AllTorrents = null;
            }
        }

        public void AddItemsToList(UTorrentList torrents, ref ArrayListDataSet dataSet)
        {
            foreach (UTorrent torrentItem in torrents)
            {
                TorrentItem tempItem = new TorrentItem();
                tempItem.Name = torrentItem.Name;
                tempItem.Downloaded = torrentItem.Downloaded;
                tempItem.Size = torrentItem.Size;
                tempItem.Progress = torrentItem.Progress;
                tempItem.Parent = this;
                dataSet.Add(tempItem);
            }

        }

        private void CreateFilters(TorrentListPage page)
        {
            ArrayListDataSet list = new ArrayListDataSet(page);
            list.Add("downloading");
            list.Add("seeding");
            list.Add("all");
            Choice filters = new Choice(page, null, list);
            filters.Chosen = "downloading";

            //
            // Hook up the "filter changed" event so that we can apply the
            // active filter to our list.
            //
            // As soon as this Filters list is set, we will get an OnActiveFilterChanged
            // event which will cause us to populate the gallery.
            //

            page.ActiveFilterChanged += delegate(object sender, EventArgs e)
            {
                TorrentListPage torrentListPage = (TorrentListPage)sender;
                string activeFilter = (string)torrentListPage.Filters.Chosen;
                FilterContent(torrentListPage, activeFilter);
            };
            page.Filters = filters;
        }

        private void FilterContent(TorrentListPage page, string filterName)
        {
            //page.Content.Clear();

            switch (filterName)
            {
                case "downloading":
                    page.Content = this.DownloadingTorrents.Options;
                    break;
                case "seeding":
                    page.Content = this.SeedingTorrents.Options;
                    break;
                case "all":
                    page.Content = this.AllTorrents.Options;
                    break;
            }
        }

        private void SearchTorrents(TorrentSearchPage page)
        {
            RssFeed feed = RssFeed.Create(new Uri("http://www.tvrss.net/search/index.php?distribution_group=combined&show_name=" + page.SearchText + "&filename=&date=&quality=&release_group=&mode=rss"));
            ArrayListDataSet tempList = new ArrayListDataSet();
            foreach (RssItem item in feed.Channel.Items)
            {
                TorrentItem ti = new TorrentItem();
                ti.URL = item.Link;
                ti.Name = item.Title;
                ti.Description = item.Description;
                ti.Parent = this;
                tempList.Add(ti);
            }
            page.Content = tempList;
        }

        public TorrentListPage CreateListPage()
        {
            if (_TorrentListPageInstance == null)
            {
                _TorrentListPageInstance = new TorrentListPage();
                _TorrentListPageInstance.Description = "torrent list";

                ArrayListDataSet torrentList = new ArrayListDataSet();
                torrentList.Add(new TorrentItem());

                _TorrentListPageInstance.Content = torrentList;
                CreateFilters(_TorrentListPageInstance);
            }

            return _TorrentListPageInstance;
        }

        public TorrentSearchPage CreateSearchPage()
        {
            if (_TorrentSearchPageInstance == null)
            {
                _TorrentSearchPageInstance = new TorrentSearchPage();
                _TorrentSearchPageInstance.Description = "search : torrents";

                ArrayListDataSet torrentList = new ArrayListDataSet();
                torrentList.Add(new TorrentItem());

                _TorrentSearchPageInstance.Content = torrentList;

                _TorrentSearchPageInstance.SearchTextChanged += delegate(object sender, EventArgs e)
                {
                    TorrentSearchPage torrentSearchPage = (TorrentSearchPage)sender;
                    SearchTorrents(torrentSearchPage);
                };
            }

            return _TorrentSearchPageInstance;
        }

    }
}
